#include <myfilelog.hxx>
#include <loghelper.hxx>


#include <macro.hxx>
#include "robotmanager.hxx"
#include "action.hxx"
#include "robot.hxx"

using namespace std;

Robot::Robot(RobotManager* robotManager, bool isStanding, FileLog* filelog)
: robotManager(robotManager),
isStanding(isStanding),
isShutdownRequested(false),
_filelog(filelog)
{
	Start();
}

void Robot::Execute(Thread::Arg arg)
{
	const int MaxFailedCount = 1000;

	LOGINFO("Robot #"<<RealThreadId()<<" started...");

	int failedCount = 0;
	Action* action= NULL;
	while (!isShutdownRequested)
	{
		action = robotManager->GetReadyAction();
		if (action == NULL)
		{
			if (!isStanding && failedCount++ == MaxFailedCount)
				Shutdown();

			Thread::Yield();
			continue;
		}

		failedCount = 0;

		action->Execute();
	}

	LOGINFO("Robot #"<<RealThreadId()<<" ended.");
}

void Robot::Shutdown(void)
{
	isShutdownRequested = true;
}